import { ref } from 'vue'
import { IndexAPI, UserAPI } from '@/api'

// 类型定义
interface PageLoadOptions {
  scene?: string
  [key: string]: any
}

interface LocationResult {
  latitude: number
  longitude: number
  address?: string
}

// 常量定义
const COUNTDOWN_SECONDS = 60
const UPDATE_INTERVAL = 1000

export function useIndexPage() {
  let timer: number | null = null
  const btnTimer = ref<number | null>(null)
  const countdown = ref(0)
  const isLoading = ref(false)
  const isDetial = ref(true)
  const latitude = ref(0)
  const longitude = ref(0)
  const remindBtnText = ref('一键提醒')
  const nowTime = ref('当前时间获取失败')
  const address = ref('位置信息获取失败')
  const plateNumber = ref('车牌号码获取失败')
  const height = ref(0)
  const windowHeight = ref(0)
  const anchors = ref<number[]>([])
  const userId = ref('')

  /**
   * 监听页面加载
   */
  async function onPageLoad(res?: PageLoadOptions) {
    uni.showLoading({
      title: '加载中',
      mask: true,
    })
    // 预登录
    // #ifdef MP-WEIXIN
    await beforedLogin()
    // #endif
    console.log('onLoad', res)
    const scene = res?.scene ? decodeURIComponent(res.scene) : ''
    initFloatingPanel()
    await getLocation()
    initTime()
    await initPlateNumber(scene)
    uni.hideLoading()
  }

  /**
   * 监听页面显示
   */
  function onPageShow() {
    initTime()
  }

  /**
   * 监听页面销毁
   */
  function onPageUnmount() {
    // 清理时间更新定时器
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    // 清理倒计时定时器
    if (btnTimer.value) {
      clearInterval(btnTimer.value)
      btnTimer.value = null
    }
  }

  /**
   * 悬浮面板高度变化
   * @param height 高度对象
   * @param height.height 高度值
   */
  function handleHeightChange({ height }: { height: number }) {
    if (height === 100) {
      isDetial.value = !isDetial.value
    }
    else {
      isDetial.value = true
    }
    console.log(height)
  }

  /**
   * 地图点击事件
   * @param res 点击事件参数
   */
  function onClickMap(res: any) {
    console.log('地图点击事件:', res)
  }

  /**
   * 初始化时间
   */
  function initTime() {
    // 清理之前的定时器
    if (timer) {
      clearInterval(timer)
    }

    const update = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      const day = now.getDate()
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      nowTime.value = `${year}年${month}月${day}日 ${hour}:${minute}:${second}`
    }

    update()
    timer = setInterval(update, UPDATE_INTERVAL)
  }

  async function beforedLogin() {
    return new Promise<void>((resolve, reject) => {
      uni.login({
        provider: 'weixin', // 使用微信登录
        success(loginRes) {
          console.log(loginRes.errMsg, loginRes.code)
          if (loginRes.errMsg === 'login:ok') {
            UserAPI.beforeWxLogin(loginRes.code).then((res: any) => {
              console.log(res)
              if (res) {
                userId.value = res
              }
              resolve()
            }).catch(reject)
          }
          else {
            reject(new Error('微信登录失败'))
          }
        },
        fail: reject,
      })
    })
  }

  /**
   * 初始化悬浮面板
   */
  function initFloatingPanel() {
    const systemInfo = uni.getSystemInfoSync()
    windowHeight.value = systemInfo.windowHeight
    anchors.value = [
      100,
      Math.round(0.54 * windowHeight.value),
      Math.round(0.66 * windowHeight.value),
    ]
    height.value = anchors.value[1]
  }

  /**
   * 获取当前位置
   */
  async function getLocation() {
    return new Promise<void>((resolve) => {
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        success: (res: LocationResult) => {
          latitude.value = res.latitude
          longitude.value = res.longitude
          reverseGeocode(res.latitude, res.longitude)
          resolve()
        },
        fail: (err: any) => {
          console.error('定位失败', err)
          uni.showToast({
            title: '获取位置失败',
            icon: 'none',
          })
          resolve() // 即使失败也要 resolve，避免阻塞后续流程
        },
      })
    })
  }

  /**
   * 地址逆解析
   * @param latitude 纬度
   * @param longitude 经度
   */
  async function reverseGeocode(latitude: number, longitude: number) {
    try {
      const res = await IndexAPI.reverse(latitude, longitude)
      console.log('逆向地理编码结果:', res)
      address.value = res
    }
    catch (error) {
      console.error('逆向地理编码失败', error)
      uni.showToast({
        title: '获取位置信息失败',
        icon: 'none',
      })
    }
  }

  /**
   * 获取车辆信息（扫码时使用传入的值，测试环境默认）
   * @param scene 场景值
   */
  async function initPlateNumber(scene: string) {
    try {
      let user = scene

      if (!user || user === '' || user === 'undefined') {
        user = userId.value
      }

      const res = await IndexAPI.getPlateNumber(user)
      // 在车牌号的第二位和第三位之间添加 "·"
      if (res && typeof res === 'string' && res.length >= 3) {
        plateNumber.value = `${res.slice(0, 2)}·${res.slice(2)}`
      }
      else {
        plateNumber.value = res
      }
    }
    catch (error) {
      console.error('获取车牌号失败', error)
      uni.showToast({
        title: '获取车牌号失败',
        icon: 'none',
      })
    }
  }

  /**
   * 一键提醒
   */
  async function handleRemind() {
    if (isLoading.value || countdown.value > 0)
      return

    isLoading.value = true
    try {
      const res = await IndexAPI.remind(userId.value, address.value)
      uni.showToast({
        title: res,
        icon: 'none',
      })

      startCountdown(COUNTDOWN_SECONDS)
    }
    catch (error) {
      console.error('提醒失败:', error)
      uni.showToast({
        title: '提醒失败，请重试',
        icon: 'none',
      })
    }
    finally {
      isLoading.value = false
    }
  }

  /**
   * 提醒倒计时
   * @param seconds 倒计时秒数
   */
  function startCountdown(seconds = COUNTDOWN_SECONDS) {
    // 清理之前的倒计时
    if (btnTimer.value) {
      clearInterval(btnTimer.value)
    }

    countdown.value = seconds
    btnTimer.value = setInterval(() => {
      if (countdown.value <= 0) {
        if (btnTimer.value) {
          clearInterval(btnTimer.value)
          btnTimer.value = null
        }
        remindBtnText.value = '一键提醒'
      }
      else {
        countdown.value--
        remindBtnText.value = `${countdown.value}秒后重试`
      }
    }, UPDATE_INTERVAL)
  }

  /**
   * 跳转到后台
   */
  function handleAdmin() {
    uni.switchTab({
      url: '/pages/home/index',
      success: () => {
        console.log('跳转成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        uni.showToast({
          title: '跳转失败',
          icon: 'none',
        })
      },
    })
  }

  return {
    // 状态
    btnTimer,
    countdown,
    isLoading,
    isDetial,
    latitude,
    longitude,
    remindBtnText,
    nowTime,
    address,
    plateNumber,
    height,
    windowHeight,
    anchors,

    // 方法
    onPageLoad,
    onPageShow,
    onPageUnmount,
    handleHeightChange,
    onClickMap,
    handleRemind,
    handleAdmin,
  }
}
